<template>
  <div class="basic-setting-content pl16 pr16" style="padding: 0px;">
    <el-card>
      <!--基本信息-->
      <div class="common-form">基本信息</div>
      <!-- <el-form-item label="商品编码："><el-input v-model="form.model.productNo" class="max-w460"></el-input></el-form-item> -->
      <!-- <el-form-item label="商品类型：" :rules="[{ required: true, message: '请选择商品类型' }]" prop="model.productType">
        <el-radio-group :disabled="typeDisable || disabled" @change="onProductTypeChange"
          v-model="form.model.productType">
          <el-radio v-for="(item, index) in productTypes" :key="item.value" :label="item.name"
            :value="item.value"></el-radio>
        </el-radio-group>
      </el-form-item> -->

      <!-- 商品所属种类： -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品所属种类：" prop="model.categoryParentId">
            <el-select v-model="form.model.categoryParentId" :disabled="disabled" filterable style="width: 460px"
              size="default" @change="onModelChange">
              <el-option v-for="p in modelData" :key="p.label" :label="p.label" :value="p.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品品种:" prop="model.categoryId">
            <el-select :disabled="disabled" v-model="form.model.categoryId" size="default" filterable style="width: 460px">
              <template v-for="cat in childModelData" :key="cat.categoryId">
                <el-option :value="cat.categoryId" :label="cat.name"></el-option>
                <template v-for="two in cat.children" :key="two.categoryId">
                  <el-option :value="two.categoryId" :label="two.name" style="padding-left: 30px"></el-option>
                </template>
              </template>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品名称：" prop="model.productName">
            <el-input v-model="form.model.productName" :readonly="form.model.modelName === '种苗' &&
              form.model.productType === 1" class="max-w460" :disabled="disabled">
              <template v-if="form.model.modelName === '种苗' && form.model.productType === 1" #append>
                <el-button size="small" @click="handlerSelect" :disabled="disabled">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生产基地:" prop="model.produceAddress">
            <el-select :disabled="disabled" v-model="form.model.produceAddress" size="default" filterable
              style="width: 460px">
              <template v-for="cat in form.produceAddrList" :key="cat.produceAddrId">
                <el-option :value="cat.produceAddrId" :label="cat.produceName"></el-option>
              </template>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="规格：" prop="model.productName">
            <el-select :disabled="disabled" v-model="form.model.spec">
              <el-option v-for="(item, index) in modelDic[form.model.modelName]" :label="item" :value="item"
                :key="index"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="form.model.isPreview == 1" label="预告开启购买时间" prop="model.previewTime">
            <el-date-picker style="width: 460px" v-model="form.model.previewTime" type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品属性：">
            <el-radio-group :disabled="disabled" v-model="form.model.isVirtual">
              <el-radio :label="0" border>实物商品</el-radio>
              <el-radio :label="1" border>虚拟商品(无需发货)</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="付款时限(分钟)：" prop="model.payDead">
            <el-input type="number" :disabled="disabled" min="0" v-model="form.model.payDead" class="max-w460"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-form-item label="销售状态：">
        <el-radio-group v-model="form.model.productStatus">
          <el-radio :label="10">立即上架</el-radio>
          <el-radio :label="20">放入仓库</el-radio>
        </el-radio-group>
      </el-form-item>-->
      <!-- <el-form-item label="预告商品：">
        <el-radio-group v-model="form.model.isPreview">
          <el-radio :label="1">开启</el-radio>
          <el-radio :label="0">关闭</el-radio>
        </el-radio-group>
      </el-form-item>-->
      
      <el-form-item label="商品图集" prop="model.image">
        <div class="draggable-list">
          <draggable class="wrapper" v-model="form.model.image">
            <template #item="{ element, index }">
              <div class="item file-img">
                <img id="viewer" v-img-url="element.filePath" />
                <div class="bottom-shade" @click.stop>
                  <a href="javascript:void(0)" @click.stop="deleteImg(index, 'tj')">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </a>
                  <a href="javascript:void(0)" style="margin-left: 10px;" @click="downImg(element.filePath)">
                    <el-icon>
                      <Download />
                    </el-icon>
                  </a>
                  <a href="javascript:void(0)" style="margin-left: 10px;" @click="cropperVisibleFunc(element.filePath)">
                    <el-icon>
                      <ZoomIn />
                    </el-icon>
                  </a>
                </div>
                <!-- <a href="javascript:void(0);" v-if="!disabled" class="delete-btn" @click.stop="deleteImg(index, 'tj')">
                  <el-icon>
                    <CloseBold />
                  </el-icon>
                </a> -->
              </div>
            </template>
          </draggable>
          <div class="item img-select" v-if="!disabled" @click="openProductUpload('image', 'image', 'tj')">
            <el-icon>
              <Plus />
            </el-icon>
          </div>
        </div>
        <div class="gray9">建议上传尺寸相同的图片，建议尺寸比例为1:1，建议商品头像像素为：80px*70px</div>
      </el-form-item>
      
      <!-- <el-form-item label="运费模板：" 
      :rules="[{ required: true, message: '选择运费模板' }]" 
      prop="model.deliveryId" v-if="form.model.isVirtual==0">
        <el-select v-model="form.model.deliveryId" style="width: 460px;">
          <el-option v-for="item in form.delivery"
          :value="item.deliveryId" :key="item.deliveryId" :label="item.name"></el-option>
        </el-select>
      </el-form-item>-->
      <!--其他设置-->
      <!-- <div class="common-form mt50">其他设置</div>
      <el-form-item label="商品属性：">
        <el-radio-group v-model="form.model.isVirtual">
          <el-radio :label="0">实物商品</el-radio>
          <el-radio :label="1">虚拟商品(无需发货)</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="运费模板：" :rules="[{ required: true, message: '选择运费模板' }]" prop="model.deliveryId" v-if="form.model.isVirtual==0">
        <el-select v-model="form.model.deliveryId" style="width: 460px;">
          <el-option v-for="item in form.delivery" :value="item.deliveryId" :key="item.deliveryId" :label="item.name"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="初始销量：">
        <el-input type="number" min="0" v-model="form.model.salesInitial" class="max-w460"></el-input>
      </el-form-item>
      <el-form-item label="商品排序：" :rules="[{ required: true, message: ' ' }]" prop="model.productSort">
        <el-input type="number" min="0" v-model="form.model.productSort" class="max-w460"></el-input>
      </el-form-item>
      <el-form-item label="限购数量：" :rules="[{ required: true, message: ' ' }]" prop="model.limitNum">
        <el-input type="number" min="0" v-model="form.model.limitNum" class="max-w460"></el-input>
        <div class="gray9">每个会员购买的最大数量，0为不限购</div>
      </el-form-item>
      <el-form-item label="发货类型：" v-if="form.model.isVirtual==1">
        <el-radio-group v-model="form.model.virtualAuto">
          <el-radio :label="1">自动</el-radio>
          <el-radio :label="0">手动</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="虚拟内容：" :rules="[{ required: true, message: '请填写虚拟内容' }]" prop="model.virtualContent" v-if="form.model.isVirtual==1">
        <el-input type="text" v-model="form.model.virtualContent" class="max-w460"></el-input>
        <div class="gray9">虚拟物品内容</div>
      </el-form-item>
      <el-form-item label="会员等级限制：">
        <el-select v-model="form.model.gradeIds" multiple placeholder="请选择" style="width: 460px;">
          <el-option
            v-for="item in form.gradeList"
            :key="item.gradeId"
            :label="item.name"
            :value="item.gradeId">
          </el-option>
        </el-select>
        <div class="gray9">仅设置的等级会员可购买，不设置则都可以购买</div>
      </el-form-item>-->
    </el-card>
    
    <!--商品图片组件-->
    <Upload v-if="isProductUpload" :config="config" :isupload="isProductUpload" @returnImgs="returnProductImgsFunc">上传图片
    </Upload>
    <!-- 选择商品 -->
    <ProdcutSelect :isProduct="selectShow" :default-cate-id="defaultCateId" :islist="false"
      @closeDialog="onProductSave" />
    <!-- 查看图片 -->
    <el-dialog top="5vh" width="" title="查看图片" v-model="cropperVisible" :close-on-click-modal="false"
      custom-class="upload-dialog" :close-on-press-escape="false" @close="cropperVisible = false" :width="dialogWidth"
      :append-to-body="true">
      <img :src="cropperVisibleImg" style="width: 100%;" alt="">

    </el-dialog>
  </div>
</template>

<script>
import Viewer from 'viewerjs'
import 'viewerjs/dist/viewer.css'
import Upload from "@/components/file/Upload.vue";
import draggable from "vuedraggable";
import ProdcutSelect from '../ProdcutSelect.vue'
import PorductApi from "@/api/product.js";
export default {
  components: {
    Upload,
    draggable,
    ProdcutSelect
  },
  data() {
    return {
      isProductUpload: false,
      config: {},
      cropperVisible: false,
      cropperVisibleImg: '',
      file_name: "image",
      fileTypeValue: 'fm',
      modelData: [], //种类，
      childModelData: [], //品种
      modelDic: {
        '种子': ['千粒', '粒'],
        '种苗': ['株'],
        '种球': ['颗'],
        '农资': ['袋', '瓶']
      },
      productTypes: [
        { name: '普通商品', value: 1 },
        { name: '拼团活动', value: 2 },
        { name: '秒杀活动', value: 3 },
        { name: '预售活动', value: 4 },
        { name: '进口苗活动', value: 5 },
        { name: '特惠活动', value: 6 },

      ],
      selectShow: false,
      defaultCateId: '',
      disabled: false,
      typeDisable: false
    };
  },
  watch: {
    'form.category': {
      deep: true,
      immediate: true,
      handler(n, v) {
        if (n && n.length > 0) {
          this.modelData = n.map(f => {
            return {
              label: f.name,
              value: f.categoryId
            }
          })
          const item = this.modelData.find(f => f.label === '种子')
          if (item) {
            this.defaultCateId = item.value
          }
        }
      }
    },
    'form.model.categoryParentId': {
      deep: true,
      immediate: true,
      handler(n, v) {
        if (n) {
          this.setModelChild(n)
        }
      }
    },
    'form.model.productType': {
      deep: true,
      immediate: true,
      handler(n, v) {
        if (n) {

          const item = this.productTypes.find(f => f.value === n)
          if (item) {
            this.form.model.productTypeName = item.name
          }
        }
      }
    }
  },
  inject: ["form"],
  created() {
    console.log(this.form, 'form')
    this.disabled = this.$route.query.scene === 'view'
    this.typeDisable = this.$route.query.scene === 'edit'
  },
  methods: {
    cropperVisibleFunc(url) {
      viewer.value = new Viewer(document.getElementById('viewer'), {
        inline: false, // 内联模式
        button: true, // 是否显示关闭按钮
        loading: true, // 图片加载状态
        zIndex: 9999, // 设置层级
      })
      viewer.value.show()
    },
    // 下载
    downImg(url) {
      var image = new Image();
      image.setAttribute("crossOrigin", "anonymous");
      var _this = this;
      image.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        var context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        var url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
        var a = document.createElement("a"); // 生成一个a元素
        var event = new MouseEvent("click"); // 创建一个单击事件
        a.download = _this.form.model.productName; // 设置图片名称
        a.href = url; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
      };
      image.src = url
    },
    onProductTypeChange(e) {
      this.form.model.productName = ''
      this.form.model.relateProductId = ''
      this.form.model.relationProductId = ''
      console.log(e, 'eee')
      const item = this.productTypes.find(f => f.name === e)
      if (item) {
        this.form.model.productType = item.value
      }
    },
    handlerSelect() {
      this.selectShow = true
    },
    onProductSave(data) {
      console.log(data, '7777')
      if (data && data.params) {
        if (data.params.length > 0) {
          const item = data.params[0]
          this.form.model.productName = item.productName
          this.form.model.relateProductId = item.productId
          this.form.model.relationProductId = item.productId
          this.loadSpecData(item.productId)
        } else {
          //单选 
          const item = data.params
          this.form.model.productName = item.productName
          this.form.model.relateProductId = item.productId
          this.form.model.relationProductId = item.productId
          this.loadSpecData(item.productId)
        }
      }

      this.selectShow = false
    },
    loadSpecData(productId) {
      const $this = this
      PorductApi.getEditData(
        {
          productId: productId,
          scene: 'edit'
        },
        true
      ).then(result => {
        if (result.data && result.data.model) {
          //设置默认的规格
          const ndata = result.data.model
          $this.form.model.specList = []
          if (ndata.sku && ndata.sku.length > 0) {
            $this.form.model.specList = ndata.sku.map(f => {
              return {

                disabled: true,
                ...f,
                sku: '',
                minBuyCount: 0,
                produceAddress: '',
                stockNum: 0,
                productPrice: 0,
                tenThousandPrice: 0,
                lakhPrice: 0
              }
            })
          }


        }
      })
    },
    onModelChange(e) {
      this.form.model.categoryId = ''
      const options = this.form.category
      const item = options.find(f => f.categoryId === e)
      if (!this.modelDic[item.name]) {
        this.modelDic[item.name] = ['千粒', '粒', '株', '颗', '袋', '瓶']
      }
      this.form.model.modelName = item.name
      this.childModelData = item.children
      this.form.model.spec = ''
      // this.form.model.productName = ''
      this.form.model.relateProductId = ''
      this.form.model.relationProductId = ''
      this.form.model.specList = []

    },
    setModelChild(e) {
      if (this.$route.query.scene === 'edit' || this.$route.query.scene === 'view') {
        const options = this.form.category
        const item = options.find(f => f.categoryId === e)
        this.form.model.modelName = item.name
        this.childModelData = item.children
      }
    },
    /*打开上传图片*/
    openProductUpload: function (file_type, file_name, filedType) {
      this.file_name = file_name;
      this.fileTypeValue = filedType
      if (file_type == "image") {
        this.config = {
          total: 9,
          fileType: "image",
        };
      } else {
        this.config = {
          total: 1,
          fileType: "video",
        };
      }
      this.isProductUpload = true;
    },

    /*上传商品图片*/
    returnProductImgsFunc(e) {
      if (e != null) {
        if (this.file_name == "video") {
          this.form.model.videoId = e[0].fileId;
          this.form.model.videoFilePath = e[0].filePath;
        } else if (this.file_name == "image") {
          console.log('eee', e, this.form.model)
          let imgs = this.form.model.image.concat(e)
          // 兼容后端
          for (let i = 0; i < imgs.length; i++) {
            if (typeof imgs[i].imageId == "undefined") {
              imgs[i].imageId = imgs[i].fileId;
            }
          }
          this.form.model.image = imgs;
        } else if (this.file_name == "poster") {
          this.form.model.posterId = e[0].fileId;
          this.form.model.posterFilePath = e[0].filePath;
        }
      }
      this.isProductUpload = false;
    },

    /*删除商品图片*/
    deleteImg(index, type) {
      this.form.model.image.splice(index, 1);
    },
    delVideo() {
      this.form.model.videoId = 0;
      this.form.model.video = {};
    },
  },
};
</script>

<style scoped>
.file-img {
  position: relative;
}

.file-img:hover .bottom-shade {
  display: block;
}

.bottom-shade {
  position: absolute;
  bottom: 0px;
  left: 0;
  background: rgba(0, 0, 0, 0.7);
  height: 26px;
  line-height: 26px;
  width: 100%;
  display: none;
  transform: all 0.2s ease-out 0s;
  color: #FFFFFF;
  text-align: center;
}

.bottom-shade a {
  color: #FFFFFF;
}
</style>
